package com.lagou.order.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lagou.common.pojo.Goods;
import com.lagou.common.pojo.OrderInfo;
import com.lagou.order.feign.GoodsFeign;
import com.lagou.order.mapper.OrderMapper;
import com.lagou.order.mapper.PurchaseItemMapper;
import com.lagou.order.vo.QueryCondition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author cyt
 * @date 2020/11/24
 */

@RestController
@RequestMapping("order")
public class OrderController {
    @Autowired
    private OrderMapper orderMapper;

    @GetMapping("/query/{id}")
    public OrderInfo queryById(@PathVariable Integer id){
        return orderMapper.selectById(id);
    }

    @PostMapping("/query/page/{index}")
    public Map<Object, Object> query(@PathVariable  int index, @RequestBody QueryCondition queryCondition){

        System.out.println("9100");

        QueryWrapper<OrderInfo> objectQueryWrapper = new QueryWrapper<>();
        Page<OrderInfo> orderPage = new Page<>(index, 10);
        System.out.println(queryCondition.toString());
        if(queryCondition.getMinTime() != null){
            objectQueryWrapper.ge("create_time", queryCondition.getMinTime());
        }else if(queryCondition.getMaxTime() != null){
            objectQueryWrapper.le("create_time", queryCondition.getMaxTime());
        }else if(queryCondition.getOrderStatus() != null){
            objectQueryWrapper.eq("status", queryCondition.getOrderStatus().getCode());
        }

        Page<OrderInfo> selectPage = orderMapper.selectPage(orderPage, objectQueryWrapper);

        Map<Object, Object> result = new HashMap<>();
        result.put("List",selectPage.getRecords());
        result.put("total", selectPage.getTotal());

        return result;


    }

    @Autowired
    private GoodsFeign goodsFeign;

    @Autowired
    private PurchaseItemMapper purchaseItemMapper;

    @GetMapping("/goods/query/{orderId}")
    public List<Goods> findGoodsInOrder(@PathVariable Integer orderId){
        List<Integer> itemIds = purchaseItemMapper.findItemIdsByOrderId(orderId);

        List<Goods> goods = itemIds.stream()
                .map(itemId -> goodsFeign.queryById(itemId))
                .collect(Collectors.toList());

        return goods;


    }



}
